# coding: utf-8

import os
import urllib
from datetime import date

from flask import request, abort
from flask_restful import Api

from app.api_v2.views import AppAuthResource, Response
from app.models import get_timestamp
from common.utils import ImageUtils, QiNiu

api = Api()


@api.resource('/<dir_name>/pictures')
class ProductPictureResource(AppAuthResource):
    """
    create by ld_wu 2018-01-15
    以文件方式上传产品图片
    """

    def post(self, dir_name):
        upload_file = request.files['file']
        if dir_name == 'product':
            sub_dir = 'product_images'
        elif dir_name == 'time_line':
            sub_dir = 'time_lines'
        else:
            abort(404)
        save_file_dir = os.path.join(
            os.path.dirname(os.path.dirname(os.path.abspath(__file__))),
            'api/img/{}'.format(sub_dir)
        )

        ext = upload_file.filename.split('.')[-1]
        if not os.path.exists(save_file_dir):
            os.makedirs(save_file_dir)
        file_name = '{}_{}'.format(get_timestamp(), upload_file.filename)
        save_file_path = os.path.join(
            save_file_dir,
            file_name
        )
        upload_file.save(save_file_path)
        host = os.environ.get('img_host')
        url = urllib.parse.urljoin(host, '{}/{}'.format(sub_dir, file_name))

        thumbnail_url = ''
        if ImageUtils.is_image_type(ext):
            try:
                thumbnail = ImageUtils.resize(save_file_path)
                thumbnail_filename = '{filename}_thumbnail.{format}'.format(
                    format=ext,
                    filename=file_name
                )
                thumbnail.save(os.path.join(save_file_dir, thumbnail_filename))
                new_thumbnail_filename = '{filename}_thumbnail'.format(
                    filename=file_name
                )
                os.rename(
                    os.path.join(save_file_dir, thumbnail_filename),
                    os.path.join(save_file_dir, new_thumbnail_filename)
                )

                thumbnail_url = urllib.parse.urljoin(
                    host, '{}/{}'.format(sub_dir, new_thumbnail_filename)
                )
            except OSError as e:
                print(e)

        return Response(
            body={
                'url': url,
                'thumbnail_url': thumbnail_url,
            }
        )

    def put(self, dir_name):
        """
        create by ld_wu 2018-03-07
        上传文件到七牛
        """
        upload_file = request.files['file']
        if dir_name == 'product':
            sub_dir = 'product_images'
        elif dir_name == 'time_line':
            sub_dir = 'time_lines'
        else:
            abort(404)

        file_name = '{}_{}'.format(get_timestamp(), upload_file.filename)

        today = date.today()
        upload_key = '{}/{}{}/{}'.format(
            sub_dir, today.year, today.month, file_name
        )

        bucket_name = ''
        url = QiNiu().upload(bucket_name, upload_key, upload_file.read())

        return Response(
            body={
                'url': url
            }
        )

